import React, { Component } from 'react';
import _ from 'lodash';

export default (WrappedComponent) => {
  class DebounceWrapperComponent extends Component {
    constructor(props) {
      super();
      this.debounceClick = this.debounceClick.bind(this);
      this.handleDebounceClick = _.debounce(this.debounceClick, REACT_APP_DEBOUNCE_WAIT_TIMER, {
        leading: true,
        trailing: false,
      });
    }

    componentWillUnmount() {
      this.handleDebounceClick.cancel();
    }

    debounceClick(...args) {
      this.props.onClick && this.props.onClick(...args);
    }

    render() {
      return <WrappedComponent {...this.props} onClick={this.handleDebounceClick} />;
    }
  }

  return (props) => <DebounceWrapperComponent {...props} />;
};
